package com.huaxindata.im.main.chat;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxin.common.BaseApp;
import com.huaxin.common.message.BaiduMapActivity;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxindata.common.util.ToastUtil;
import com.huaxindata.common.view.CirclePageIndicator;
import com.huaxindata.im.R;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.main.chat.Helper.FileHelper;
import com.huaxindata.im.main.chat.Helper.LocationHelper;
import com.huaxindata.im.main.chat.Helper.TextHelper;
import com.huaxindata.im.main.chat.Helper.VoiceHelper;
import com.huaxindata.im.main.chat.adapter.ChatAdapter;
import com.huaxindata.im.main.chat.adapter.EmojiPagerAdapter;
import com.huaxindata.im.main.contactview.friend.FriendInfoActivity;
import com.huaxindata.im.main.contactview.group.GroupInfoActivity;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.db.ContactStore;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.model.emoji.EmotionUtil;
import com.huaxindata.im.model.emoji.HxEmotion;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatSysMessageBody;
import com.huaxindata.im.service.MessageService;
import com.huaxindata.im.service.OnMessageReceiveListener;
import com.huaxindata.im.service.OnMessageSendListener;
import com.huaxindata.im.util.FileUtil;
import com.huaxindata.im.util.Log;
import com.huaxindata.im.util.SharePreferenceUtil;
import com.huaxindata.im.view.TouchLinearLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.List;

/**
 * Created by Administrator on 2017/8/31.
 * 聊天的主界面
 */

public class ConversationActivity extends AppCompatActivity implements
        EmojiPagerAdapter.OnEmojiItemClickListenner,
        ConversationManager.OnSendMessageListener,
        ConversationManager.OnUnSubscribeListener,
        OnMessageReceiveListener {

    private static final String TAG = "ConversationActivity";
    private ImageButton titleIcon;
    private TextView    titleInfo;
    private TextView    title;

    private AvatarImageView mGroupInfoImg;//点击进入群资料界面

    private RelativeLayout topBar;
    private ImageButton    btnSetModeVoice;
    private ImageButton    btnSetModeKeyboard;
    private LinearLayout   btnPressToSpeak;

    private EditText msgEditTxt;//发送消息的编辑框

    private RelativeLayout editTextLayout;
    private ImageButton    ivEmoticonsNormal;
    private ImageButton    ivEmoticonsChecked;
    private ImageButton    btnMore;
    private Button         btnSend;
    private LinearLayout   rlBottom;

    private ViewPager           emojiViewPager;
    private CirclePageIndicator circlePageIndicator;

    private LinearLayout emotionContainer;//表情按钮弹出框容器

    private ImageView btnTakePicture;
    private ImageView btnPicture;
    private ImageView btnVideo;
   // private ImageView btnFile;
    private ImageView btnLocation;
    //private ImageView btnSvg;
   // private ImageView btnDevice;

    private GridLayout fileBtnContainer;//发送图片，视频，文件等的容器

    private LinearLayout bottomRootContainer;//加号按钮弹出框根容器

    private ProgressBar pbLoadMore;//聊天界面下拉加载更多的进度条
    private ListView    mMsgShowLv;//显示消息的listView

    private ImageView      micImage;
    private TextView       recordingHint;
    private RelativeLayout recordingContainer;

    private TouchLinearLayout rootLayout;//xml文件的根布局

    //聊天界面的内容根布局
    private FrameLayout mContentView;

    private InputMethodManager manager;
    //聊天界面的适配器
    private ChatAdapter        mChatAdapter;

    private boolean mIsBind = false;
    private MessageService                 mMessageService;
    private List<HxEmotion>                mHxEmotionList;
    private Contact                        mChatObject;//当前聊天的对象
    private VoiceHelper.PressToSpeakListen mPressToSpeakListen;
    private File                           mVideoFile;
    private File                           mImageFile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ConversationManager.addOnSendMessageListener(this);
        ConversationManager.addSubscribeListener(this);
        findView();
        initView();
        initData();
        bindToService();
    }

    private void findView() {
        titleIcon = (ImageButton) findViewById(R.id.title_icon);
        titleInfo = (TextView) findViewById(R.id.title_info);
        title = (TextView) findViewById(R.id.title);
        mGroupInfoImg = (AvatarImageView) findViewById(R.id.add_people);//点击进入群资料界面
        topBar = (RelativeLayout) findViewById(R.id.top_bar);
        btnSetModeVoice = (ImageButton) findViewById(R.id.btn_set_mode_voice);
        btnSetModeKeyboard = (ImageButton) findViewById(R.id.btn_set_mode_keyboard);
        btnPressToSpeak = (LinearLayout) findViewById(R.id.btn_press_to_speak);
        msgEditTxt = (EditText) findViewById(R.id.et_sendmessage);//发送消息的编辑框
        editTextLayout = (RelativeLayout) findViewById(R.id.edittext_layout);
        ivEmoticonsNormal = (ImageButton) findViewById(R.id.iv_emoticons_normal);
        ivEmoticonsChecked = (ImageButton) findViewById(R.id.iv_emoticons_checked);
        btnMore = (ImageButton) findViewById(R.id.btn_more);
        btnSend = (Button) findViewById(R.id.btn_send);
        rlBottom = (LinearLayout) findViewById(R.id.rl_bottom);
        emojiViewPager = (ViewPager) findViewById(R.id.activity_chat_emotion_viewPager);
        circlePageIndicator = (CirclePageIndicator) findViewById(R.id.activity_chat_pageIndicator);
        emotionContainer = (LinearLayout) findViewById(R.id.ll_face_container);//表情按钮弹出框容器
        btnTakePicture = (ImageView) findViewById(R.id.btn_take_picture);
        btnPicture = (ImageView) findViewById(R.id.btn_picture);
        btnVideo = (ImageView) findViewById(R.id.btn_video);
    //    btnFile = (ImageView) findViewById(R.id.btn_file);
        btnLocation = (ImageView) findViewById(R.id.btn_location);
      //  btnSvg = (ImageView) findViewById(R.id.btn_svg);
      //  btnDevice = (ImageView) findViewById(R.id.btn_device);
        fileBtnContainer = (GridLayout) findViewById(R.id.ll_btn_container);//发送图片，视频，文件等的容器
        bottomRootContainer = (LinearLayout) findViewById(R.id.bottom_root_layout);//加号按钮弹出框根容器
        pbLoadMore = (ProgressBar) findViewById(R.id.pb_load_more);//聊天界面下拉加载更多的进度条
        mMsgShowLv = (ListView) findViewById(R.id.list);//显示消息的listView
        micImage = (ImageView) findViewById(R.id.mic_image);
        recordingHint = (TextView) findViewById(R.id.recording_hint);
        recordingContainer = (RelativeLayout) findViewById(R.id.recording_container);
        rootLayout = (TouchLinearLayout) findViewById(R.id.root_layout);//xml文件的根布局
        //聊天界面的内容根布局
        mContentView = (FrameLayout) findViewById(R.id.activity_chat_contentView);
    }

    private void initView() {
        ivEmoticonsNormal.setVisibility(View.VISIBLE);
        ivEmoticonsChecked.setVisibility(View.GONE);

        mHxEmotionList = EmotionUtil.getTotalEmotion();
        emojiViewPager.setAdapter(new EmojiPagerAdapter(getApplicationContext(), mHxEmotionList, this));
        circlePageIndicator.setViewPager(emojiViewPager);

        editTextLayout.requestFocus();

        // 监听文字框
        msgEditTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    btnMore.setVisibility(View.GONE);
                    btnSend.setVisibility(View.VISIBLE);
                } else {
                    btnMore.setVisibility(View.VISIBLE);
                    btnSend.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }



    public void initData() {
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mChatObject = ConversationManager.getChatObject();
        if (mChatObject == null) {
            return;
        }
        mChatObject.showImageIcon(this, mGroupInfoImg, null);
        title.setText(mChatObject.getNickName());
        // updateMessageStore();
        createListView();
    }

    protected void createListView() {
        //此处开始加载消息
        // 显示消息
        mChatAdapter = new ChatAdapter(getApplicationContext(), rootLayout, mMsgShowLv, mChatObject);
        mMsgShowLv.setAdapter(mChatAdapter);
        //设置语音监听
        mPressToSpeakListen = new VoiceHelper.PressToSpeakListen(this, recordingContainer,
                recordingHint, micImage, mChatAdapter);
        btnPressToSpeak.setOnTouchListener(mPressToSpeakListen);
        final ChatMessage message = new ChatMessage(ChatMessageBody.Type.SYSTEM, mChatAdapter.getCount() == 0 ?
                ChatAdapter.TIP_1 : ChatAdapter.TIP_2);
        message.timestamp = 0;
        mChatAdapter.addMessage(message);
        loadMessageFromDB();
        mChatAdapter.refreshToLast();

        mMsgShowLv.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mChatAdapter.isPopWindowShow()) {
                    return false;
                }
                hideSoftInput();
                bottomRootContainer.setVisibility(View.GONE);
                ivEmoticonsNormal.setVisibility(View.VISIBLE);
                ivEmoticonsChecked.setVisibility(View.GONE);
                emotionContainer.setVisibility(View.GONE);
                fileBtnContainer.setVisibility(View.GONE);
                return false;
            }
        });
        //布局发生变化时，滑动至底部
        rootLayout.setLayoutChangeListener(new TouchLinearLayout.LayoutChangeListener() {
            int normal = 0;

            @Override
            public void onLayoutChange(int l, int t, int r, int b) {
                if (normal == 0) {
                    normal = rootLayout.getHeight();
                }
                mChatAdapter.refreshToLast();
            }
        });
    }

    /**
     * 获取聊天消息
     */
    private void loadMessageFromDB() {
        mChatAdapter.clearMessage();
        List<ChatMessage> messageList = null;
        if (mChatObject instanceof ContactPerson) {
            //消息列表需要把添加好友请求的消息过滤掉
            messageList = MessageStore.queryByClientIdFilterReqF(mChatObject.getClientId(),
                    UserManager.getClientId());
        } else if (mChatObject instanceof ContactGroup) {
            messageList = MessageStore.queryByGroupId(((ContactGroup) mChatObject)
                    .getGroupClientId());
        }
        mChatAdapter.addMessage(messageList);
        mChatAdapter.notifyDataSetChanged();
    }

    /**
     * 绑定到后台接收消息的service
     */
    private void bindToService() {
        Intent intent = new Intent(this, MessageService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        mIsBind = true;
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMessageService = ((MessageService.MyBinder) service).getService();
            mMessageService.addMessageReceiveListener(ConversationActivity.this);
            mIsBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMessageService = null;
        }
    };

    private void unBindService() {
        if (mIsBind) {
            unbindService(mServiceConnection);
            mIsBind = false;
        }
    }

    /**
     * 在聊天界面收到给当前聊天对象的消息，则直接显示
     * 系统消息不在这里展示
     *
     * @param chatMessage
     */
    @Override
    public void receiveMessage(ChatMessage chatMessage) {

        //非当前聊天对象消息不处理
        if (!mChatObject.clientId.equals(chatMessage.sender)){
            return;
        }

        //如果是系统消息，则只处理同意添加回复  群解散
        if (chatMessage.type == ChatMessageBody.Type.SYSTEM) {
            ChatSysMessageBody chatSysMessageBody = (ChatSysMessageBody) chatMessage.getMessageBody();
            String action = chatSysMessageBody.getAction();

            if (ChatSysMessageBody.SysMessageType.ACTION_RESP_FED.equals(action)) {
                    //同意添加
                    if ("2".equals(chatSysMessageBody.getSystemMessageInfo()[2])){
                        ToastUtil.showToast(this,mChatObject.nickName+"解除了与你的好友关系");
                        return;
                    }else if (!"1".equals(chatSysMessageBody.getSystemMessageInfo()[2])){
                        return;
                    }
            }else if (!ChatSysMessageBody.SysMessageType.ACTION_DESTROY_GROUP.equals(action)){
                return;
            }
        }

        //语音消息，下载完成后，需通过adpter及时刷新语音时长
        if (chatMessage.type==ChatMessageBody.Type.VOICE){
            FileHelper.downLoadFileMessage(chatMessage,this,mChatAdapter);
        }
        mChatAdapter.addMessage(chatMessage);
        mChatAdapter.notifyDataSetChanged();

        //更新常用联系人
        updateMessageStore(chatMessage);
        //更新收到的消息为已读状态，1表示已读
        MessageStore.updateReadingState(chatMessage.timestamp, chatMessage.sender, 1);
    }

    /**
     * 发送消息
     *
     * @param message
     */
    @Override
    public void onSendMessage(final ChatMessage message) {
        String topic = "chat/" + message.receiver;
        mMessageService.sendMessage(topic, message, new OnMessageSendListener() {
            @Override
            public void sendSuccess(ChatMessage message) {
                //更新最近联系人表
                updateMessageStore(message);
                Log.e(TAG, "xxx==发送消息成功：" + message.message);
                MessageStore.updateSendingStatus(message.timestamp, message.sender, ChatMessage.Status.SUCCESS);
                message.messageState = ChatMessage.Status.SUCCESS;
                mChatAdapter.notifyDataSetChanged();
            }

            @Override
            public void sendFailure(ChatMessage message) {
                Log.e("xxx", "xxx==消息发送失败");
                MessageStore.updateSendingStatus(message.timestamp, message.sender, ChatMessage.Status.ERROR);
                message.messageState = ChatMessage.Status.ERROR;
                mChatAdapter.notifyDataSetChanged();
            }
        });
    }
    /**
     * 进入聊天界面更新数据库
     */
    private void updateMessageStore(ChatMessage message) {
        //将聊会次数更新一次，添加到最近的联系人中
        if (mChatObject instanceof ContactGroup) {
            ContactStore.insert(mChatObject, 2,message.timestamp);
            //更新群消息状态，将所有未读消息置为已读
            MessageStore.updateReadingStateFromGroup(mChatObject.getClientId());
        } else if (mChatObject instanceof ContactPerson) {
            ContactStore.insert(mChatObject, 1,message.timestamp);
            //更新消息状态，将所有未读消息置为已读
            MessageStore.updateReadingState(mChatObject.getClientId());
        }
        //显示在聊天记录页面中
        ContactStore.updateShow(mChatObject.getClientId(), 0);
        //更新聊天的次数
        ContactStore.updateChatCount(mChatObject.getClientId());
    }

    @Override
    public void unSubscribe(String id) {
        if (TextUtils.isEmpty(id)) {
            return;
        }
        mMessageService.unSubscribe("chat/" + id);
    }

    @Override
    public void onEmojiItemClick(int position) {
        int currentPage = emojiViewPager.getCurrentItem();
        int count = mHxEmotionList.size();
        int totalPage = count / 28;//表情包的整页数
        if (position == 27 || ((totalPage == currentPage) && count % 27 == position)) {//点击删除按钮
            msgEditTxt.onKeyDown(KeyEvent.KEYCODE_DEL, new KeyEvent(KeyEvent.ACTION_DOWN,
                    KeyEvent.KEYCODE_DEL));
            msgEditTxt.onKeyUp(KeyEvent.KEYCODE_DEL, new KeyEvent(KeyEvent.ACTION_UP,
                    KeyEvent.KEYCODE_DEL));
        } else {//点击表情
            HxEmotion emotion = mHxEmotionList.get(position + 27 * currentPage);
            input(msgEditTxt, emotion.getEmojiName());
        }
    }

    public void input(EditText editText, String emojiName) {
        if (editText == null || emojiName == null) {
            return;
        }
        int start = editText.getSelectionStart();
        int end = editText.getSelectionEnd();
        if (start < 0) {
            editText.append(emojiName);//如果输入框上没有任何内容就直接加在后面
        } else {
            editText.getText().replace(start, end, emojiName, 0, emojiName.length());
        }
    }

    @Override
    protected void onDestroy() {
        mMessageService.removeMessageReceiveListener(ConversationActivity.this);
        ConversationManager.removeOnSendMessageListener(this);
        unBindService();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImConstants.REQUEST_FILE_VIDEO:
                Log.e(TAG, "xxx====从录像界面返回聊天界面");
                if (mVideoFile == null || !mVideoFile.exists()) {
                    ToastUtil.showToast(this, "录制视频出错");
                    return;
                }
                FileHelper.sendVideoMessage(getApplicationContext(), mVideoFile, mChatAdapter);
                break;
            case ImConstants.REQUEST_LOCATION:
                if (data == null) {
                    return;
                }
                String locationAddress = data.getStringExtra(BaiduMapActivity.ADR);
                if (TextUtils.isEmpty(locationAddress)) {
                    locationAddress = BaseApp.getAddrStr();
                }
                double latitude = data.getDoubleExtra(BaiduMapActivity.LAT, 0);
                double longitude = data.getDoubleExtra(BaiduMapActivity.LNG, 0);
                if (!TextUtils.isEmpty(locationAddress)) {
                    onBtnMoreClick(bottomRootContainer);
                    LocationHelper.sendLocationMsg(latitude, longitude, locationAddress, mChatAdapter);
                } else {
                    Toast.makeText(this, "无法获取到您的位置信息", Toast.LENGTH_SHORT).show();
                }
                break;
            case ImConstants.REQUEST_FILE_IMAGE://拍照
                if (mImageFile.exists()) {
                    FileHelper.sendImageMessage(getApplicationContext(), mImageFile, mChatAdapter);
                }
                break;
            case PictureConfig.CHOOSE_REQUEST://相册
                List<LocalMedia> localMedias_2 = PictureSelector.obtainMultipleResult(data);
                for (LocalMedia media : localMedias_2) {
                    File file = new File(media.getPath());
                    if (file.exists()) {
                        FileHelper.sendImageMessage(getApplicationContext(), file, mChatAdapter);
                    }
                }
                break;
            default:
                break;
        }
        switch (resultCode) {
            case ImConstants.RESULT_CODE_EXIT:
                Log.e(TAG, "xxx====回调到聊天activity");
                this.finish();
                break;
        }
    }
    /***********************点击回调事件***************************************************/
    /**
     * 语音按钮回调事件
     *
     * @param view
     */
    public void onVoiceBtnClick(View view) {
        if (isKeyboardShown()) {
            hideSoftInput();
        }
        //android6.0以上设备需要动态权限，申请动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permission = checkSelfPermission(Manifest.permission.RECORD_AUDIO);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, 250);
                return;
            }
        }
        showVoiceMode();
    }

    /**
     * 点击语音按钮之后出现的键盘按钮
     *
     * @param view
     */
    public void onKeyboardBtnClick(View view) {
        showEditText();
    }

    /**
     * 点击文字输入框
     */
    public void editClick(View v) {
        mMsgShowLv.setSelection(mMsgShowLv.getCount() - 1);
        showEditText();
    }

    /**
     * 点击显示和隐藏表情框
     *
     * @param view
     */
    public void onEmotionClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_emoticons_normal) {
            showEmotion();
        } else if (id == R.id.iv_emoticons_checked) {
            showEditText();
        }
    }

    /**
     * 点击发送按钮
     *
     * @param view
     */
    public void onBtnSendClick(View view) {
        String text = msgEditTxt.getText().toString().trim();
        if (TextUtils.isEmpty(text)) {
            return;
        }
        TextHelper.sendText(text, mChatAdapter, mChatObject);
        msgEditTxt.setText(null);
    }

    /**
     * 点击加号按钮，显示或隐藏按钮页
     */
    public void onBtnMoreClick(View view) {
        showFileBtn();
    }

    /**
     * 点击了加号之后发送图片、视频、位置等消息
     *
     * @param view
     */
    public void onMultiMediaClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.btn_take_picture) {//照相机拍照
            String chatFileCacheDir = FileUtil.getChatFileCacheDir(this, mChatObject.getClientId());
            mImageFile = new File(chatFileCacheDir, "image_" + System.currentTimeMillis() + ".png");
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));//文件保存路径
            startActivityForResult(intent, ImConstants.REQUEST_FILE_IMAGE);
        } else if (viewId == R.id.btn_picture) {//相册选择
            PictureSelector.create(this).openGallery(PictureMimeType.ofImage()).forResult(PictureConfig.CHOOSE_REQUEST);
        } else if (viewId == R.id.btn_video) {
            String chatFileCacheDir = FileUtil.getChatFileCacheDir(this, mChatObject
                    .getClientId());
            mVideoFile = new File(chatFileCacheDir, "video_" + System.currentTimeMillis() + ".mp4");
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);//录制时长60s
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mVideoFile));
            startActivityForResult(intent, ImConstants.REQUEST_FILE_VIDEO);
        } else if (viewId == R.id.btn_location) {
            Intent intent = new Intent(this, BaiduMapActivity.class);
            intent.putExtra(BaiduMapActivity.LOOK, false);
            startActivityForResult(intent, ImConstants.REQUEST_LOCATION);
        }
    }

    /**
     * 显示编辑文本模式，并不显示键盘
     * 此模式下，只显示左边的发语音按钮，输入框，表情按钮，加号按钮
     */
    private void showEditText() {
        btnSetModeKeyboard.setVisibility(View.GONE);
        btnSetModeVoice.setVisibility(View.VISIBLE);

        editTextLayout.setVisibility(View.VISIBLE);
        btnPressToSpeak.setVisibility(View.GONE);

        ivEmoticonsNormal.setVisibility(View.VISIBLE);
        ivEmoticonsChecked.setVisibility(View.GONE);

        if (bottomRootContainer.isShown()) {
            lockContentHeight();
            bottomRootContainer.setVisibility(View.GONE);
            fileBtnContainer.setVisibility(View.GONE);
            emotionContainer.setVisibility(View.GONE);
            showSoftInput();
            unlockContentHeightDelayed();
        } else {
            showSoftInput();
        }
        msgEditTxt.requestFocus();
    }

    /**
     * 点击发送语音按钮，显示语音界面
     */
    private void showVoiceMode() {
        btnSetModeKeyboard.setVisibility(View.VISIBLE);
        btnSetModeVoice.setVisibility(View.GONE);

        editTextLayout.setVisibility(View.GONE);
        btnPressToSpeak.setVisibility(View.VISIBLE);

        ivEmoticonsNormal.setVisibility(View.VISIBLE);
        ivEmoticonsChecked.setVisibility(View.GONE);

        btnMore.setVisibility(View.VISIBLE);
        btnSend.setVisibility(View.GONE);

        bottomRootContainer.setVisibility(View.GONE);
        fileBtnContainer.setVisibility(View.GONE);
        emotionContainer.setVisibility(View.GONE);
    }

    /**
     * 点击表情按钮，显示表情栏
     */
    private void showEmotion() {
        //左边的语音按钮
        btnSetModeKeyboard.setVisibility(View.GONE);
        btnSetModeVoice.setVisibility(View.VISIBLE);
        //中间的输入框和点击说话按钮
        editTextLayout.setVisibility(View.VISIBLE);
        btnPressToSpeak.setVisibility(View.GONE);
        //表情按钮
        ivEmoticonsNormal.setVisibility(View.GONE);
        ivEmoticonsChecked.setVisibility(View.VISIBLE);
        //加号按钮
        btnMore.setVisibility(View.VISIBLE);
        btnSend.setVisibility(View.GONE);
        /**
         * 如果下面的根布局已经是显示状态，说明发送文件容器打开了，则锁定内容高度
         * 如果没有显示，则让其显示,如果此时键盘是显示状态，也锁定内容高度
         */
        int height = getKeyboardHeight();
        if (isKeyboardShown()) {
            lockContentHeight();
            hideSoftInput();
            fileBtnContainer.setVisibility(View.GONE);
            bottomRootContainer.getLayoutParams().height = height;
            bottomRootContainer.setVisibility(View.VISIBLE);
            emotionContainer.setVisibility(View.VISIBLE);
            unlockContentHeightDelayed();
        } else if (bottomRootContainer.isShown()) {
            fileBtnContainer.setVisibility(View.GONE);
            emotionContainer.setVisibility(View.VISIBLE);
        } else {
            bottomRootContainer.getLayoutParams().height = height;
            bottomRootContainer.setVisibility(View.VISIBLE);
            emotionContainer.setVisibility(View.VISIBLE);
        }

        //        voiceListenerHelper.cancel();
        msgEditTxt.requestFocus();
    }

    /**
     * 点击加号按钮，显示文件栏
     */
    private void showFileBtn() {

        btnSetModeKeyboard.setVisibility(View.GONE);
        btnSetModeVoice.setVisibility(View.VISIBLE);

        editTextLayout.setVisibility(View.VISIBLE);
        btnPressToSpeak.setVisibility(View.GONE);

        ivEmoticonsNormal.setVisibility(View.VISIBLE);
        ivEmoticonsChecked.setVisibility(View.GONE);

        btnMore.setVisibility(View.VISIBLE);
        btnSend.setVisibility(View.GONE);
        /**
         * 如果下面的根布局已经是显示状态，说明表情容器打开了，则锁定内容高度
         * 如果没有显示，则让其显示
         */
        int height = getKeyboardHeight();
        if (isKeyboardShown()) {
            lockContentHeight();
            hideSoftInput();
            bottomRootContainer.getLayoutParams().height = height;
            bottomRootContainer.setVisibility(View.VISIBLE);
            fileBtnContainer.setVisibility(View.VISIBLE);
            emotionContainer.setVisibility(View.GONE);
            unlockContentHeightDelayed();
        } else if (bottomRootContainer.isShown()) {
            emotionContainer.setVisibility(View.GONE);
            fileBtnContainer.setVisibility(View.VISIBLE);
        } else {
            bottomRootContainer.getLayoutParams().height = height;
            bottomRootContainer.setVisibility(View.VISIBLE);
            fileBtnContainer.setVisibility(View.VISIBLE);
        }
        //        voiceListenerHelper.cancel();

        msgEditTxt.requestFocus();
    }

    //弹出则为true
    public boolean isKeyboardShown() {
        return getSoftInputHeight() != 0;
    }

    //点击聊天界面的toolbar的聊天对象图片弹出聊天对象的个人资料
    public void addPeople(View v) {
        if (ConversationManager.getChatObject() instanceof ContactGroup) {
            Intent intent = new Intent(this, GroupInfoActivity.class);
            startActivityForResult(intent, ImConstants.REQUEST_CODE);
        } else {
            ContactPerson contact = (ContactPerson) ConversationManager.getChatObject();

            Intent intent = new Intent(this, FriendInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(ImConstants.CLIENT_ID, contact.getClientId());
            intent.putExtras(bundle);
            ConversationActivity.this.startActivity(intent);
        }
    }

    /**
     * 覆盖手机返回键
     */
    @Override
    public void onBackPressed() {
        hideSoftInput();
        if (bottomRootContainer.isShown()) {
            bottomRootContainer.setVisibility(View.GONE);
            ivEmoticonsNormal.setVisibility(View.VISIBLE);
            ivEmoticonsChecked.setVisibility(View.GONE);
        } else {
            //            Intent intent = new Intent(this, MainActivity.class);
            //            startActivity(intent);
            super.onBackPressed();
        }
    }

    /**
     * 此方法是实时的获取软键盘的高度，如果没有弹出软键盘，则高度为0
     *
     * @return
     */
    private int getSoftInputHeight() {
        Rect rect = new Rect();
        /**
         * decorView是window中的最顶层view，可以从window中通过getDecorView获取到decorView。
         * 通过decorView获取到程序显示的区域，包括标题栏，但不包括状态栏，将该区域的信息写入到rect中。
         */
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //获取屏幕的高度
        int screenHeight = getWindow().getDecorView().getRootView().getHeight();
        //计算软键盘的高度
        int softInputHeight = screenHeight - rect.bottom;
        /**
         * 某些Android版本下，没有显示软键盘时减出来的高度总是144，而不是零，
         * 这是因为高度是包括了虚拟按键栏的(例如华为系列)，所以在API Level高于20时，
         * 我们需要减去底部虚拟按键栏的高度（如果有的话）
         */
        if (Build.VERSION.SDK_INT >= 20) {
            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
            softInputHeight = softInputHeight - getSoftButtonsBarHeight();
        }
        //大于0，说明软键盘弹出，存一份到本地，等于0，说明没有弹出
        if (softInputHeight > 0) {
            SharePreferenceUtil.setInt(this, ImConstants.SOFT_KEY_BOARD_HEIGHT, softInputHeight);
        }
        return softInputHeight;
    }

    /**
     * 获取底部虚拟导航栏高度，在某些手机，比如华为手机上有
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public int getSoftButtonsBarHeight() {
        int softButtonsBarHeight = 0;
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindow().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        //获取可用的屏幕高度
        int usableHeight = displayMetrics.heightPixels;
        getWindow().getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
        //获取当前屏幕的真实高度
        int realHeight = displayMetrics.heightPixels;
        if (realHeight > usableHeight) {
            softButtonsBarHeight = realHeight - usableHeight;
        }
        return softButtonsBarHeight;
    }

    //获取软键盘高度，从SharePreference中获取，默认是400
    public int getKeyboardHeight() {
        return SharePreferenceUtil.getInt(this, ImConstants.SOFT_KEY_BOARD_HEIGHT, 550);
    }

    /**
     * 锁定内容高度，防止跳闪
     */
    private void lockContentHeight() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mContentView.getLayoutParams();
        params.height = mContentView.getHeight();
        params.weight = 0;
    }

    /**
     * 释放被锁定的内容高度
     */
    private void unlockContentHeightDelayed() {
        msgEditTxt.post(new Runnable() {
            @Override
            public void run() {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mContentView.getLayoutParams();
                params.height = 0;
                params.weight = 1;
            }
        });
    }

    //显示软键盘
    private void showSoftInput() {
        msgEditTxt.requestFocus();
        msgEditTxt.post(new Runnable() {
            @Override
            public void run() {
                manager.showSoftInput(msgEditTxt, 0);
            }
        });
    }

    //隐藏软键盘
    private void hideSoftInput() {
        manager.hideSoftInputFromWindow(msgEditTxt.getWindowToken(), 0);
    }

    public void onBackClick(View view) {
        hideSoftInput();
        finish();
    }
}
